import React, { Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Button, Card, Col, DatePicker, Divider, Form, message, Radio, Row, Select } from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ConditionForm from './component/ConditionForm';

import styles from '../../styles/Manage.less';

const FormItem = Form.Item;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

// 2天后的日期
const lateOf2Day = moment(new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 2));

const STATUS_OBJ_LIST = [
  { id: 0, name: 'GMV配置' },
  { id: 1, name: '大数据调整' },
  { id: 2, name: '运营调整' },
  { id: 3, name: '大数据确认' },
  { id: 4, name: '指令就绪' },
  { id: 5, name: '完成' },
];
const STATUS_OBJ = STATUS_OBJ_LIST.reduce((accu, curr) => {
  const newAccu = { ...accu };
  newAccu[curr.id] = curr.name;
  return newAccu;
}, {});

@Form.create()
@connect(({ loading }) => ({
  loading: loading.models.forecastResult,
}))
class ProgressManage extends React.Component {
  state = {
    forecastDate: lateOf2Day, // 被预测时间
    forecastDateString: lateOf2Day.format('YYYY-MM-DD'),

    lv1ClassifyType: 0, // 默认全部
    selectedCityList: [],
    selectedWarehouseList: [],
    cityList: [],
    warehouseList: [],
    data: [],
    setProgressModalVisible: false,
    instructionModalVisible: false,
  };

  // 表格字段
  columns = [
    {
      title: '日期',
      width: '10%',
      align: 'center',
      render: (text, record) => (
        <span>
          {record.forecastDate}({record.dayOfWeek})
        </span>
      ),
    },
    { title: '城市类型', width: '10%', dataIndex: 'cityType' },
    { title: '城市', width: '10%', dataIndex: 'cityName' },
    { title: '仓库', width: '10%', dataIndex: 'warehouseName' },
    { title: '1级分类', width: '10%', dataIndex: 'lv1ClassifyName' },
    {
      title: '进度',
      dataIndex: 'status',
      width: '10%',
      render: text => STATUS_OBJ[text],
    },
    {
      title: '最后操作人',
      width: '10%',
      dataIndex: 'modifier',
      render: text => (text === undefined ? '系统' : text),
    },
    {
      title: '最后修改时间',
      width: '15%',
      dataIndex: 'modified',
      render: text => <span>{moment.unix(text).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'option',
      render: (text, record) => (
        <Fragment>
          <Button onClick={() => this.sendInstructionById(record)}>发送信号</Button>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.handleSearch();
    this.listCity();
    this.listWarehouse();
  }

  listCity = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'forecastResult/listCity',
      callback: data => {
        this.setState({ cityList: data });
      },
    });
  };

  listWarehouse = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'forecastResult/listWarehouse',
      callback: data => {
        this.setState({ warehouseList: data });
      },
    });
  };

  getQueryParams = () => {
    const {
      lv1ClassifyType,
      forecastDateString,
      selectedCityList,
      selectedWarehouseList,
    } = this.state;
    const params = {};
    if (lv1ClassifyType !== 0) {
      params.lv1ClassifyType = lv1ClassifyType;
    }
    if (forecastDateString) {
      params.forecastDate = forecastDateString;
    }
    params.cityIdList = selectedCityList;
    params.warehouseIdList = selectedWarehouseList;
    return params;
  };

  // 查询操作
  handleSearch = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParams();
    dispatch({
      type: 'forecastResult/fetchProgress',
      payload: {
        params,
      },
      callback: data => this.setState({ data }),
    });
  };

  // 分页、过滤、排序处理
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const queryParams = this.getQueryParams();

    const params = {
      ...formValues,
      ...filters,
      ...queryParams,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'forecastResult/fetchProgress',
      payload: {
        params,
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },
      callback: data => this.setState({ data }),
    });
  };

  hideModal = (field, reload) => {
    this.setState({ [field]: false }, () => reload && this.handleSearch());
  };

  setProgress = ({ status, ...otherProps }) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'forecastResult/updateProgressStatusByParams',
      payload: {
        status,
        params: otherProps,
      },
      callback: () => {
        message.success('设置进度成功');
        this.hideModal('setProgressModalVisible', true);
      },
    });
  };

  renderSetProgressModel = () => {
    const { cityList, warehouseList, forecastDate, setProgressModalVisible } = this.state;
    if (!setProgressModalVisible) {
      return null;
    }
    const initParams = this.getQueryParams();
    const { loading } = this.props;
    const props = {
      initParams: { ...initParams, forecastDate },
      cityList,
      warehouseList,
      loading,
      modalVisible: true,
      title: '设置预测进度',
      statusObjList: STATUS_OBJ_LIST,
      cancelHandler: () => this.hideModal('setProgressModalVisible', false),
      confirmHandler: params => this.setProgress(params),
    };
    return <ConditionForm {...props} />;
  };

  sendInstruction = ({ forced, ...otherProps }) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'forecastResult/sendInstructionByParams',
      payload: {
        forced: !!forced,
        params: otherProps,
      },
      callback: data => {
        message.success(data);
        this.hideModal('instructionModalVisible', true);
      },
    });
  };

  sendInstructionById = ({ id }) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'forecastResult/sendInstructionByParams',
      payload: {
        forced: true,
        params: { id },
      },
      callback: data => {
        message.success(data);
        this.hideModal('instructionModalVisible', true);
      },
    });
  };

  renderInstructionModel = () => {
    const { cityList, warehouseList, forecastDate, instructionModalVisible } = this.state;
    if (!instructionModalVisible) {
      return null;
    }
    const { loading } = this.props;

    const initParams = this.getQueryParams();
    const props = {
      initParams: { ...initParams, forecastDate },
      cityList,
      loading: !!loading,
      warehouseList,
      modalVisible: true,
      title: '发送信号',
      cancelHandler: () => this.hideModal('instructionModalVisible', false),
      confirmHandler: params => this.sendInstruction(params),
    };
    return <ConditionForm {...props} />;
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
    } = this.props;
    const {
      lv1ClassifyType,
      forecastDate,
      selectedCityList,
      cityList,
      selectedWarehouseList,
      warehouseList,
      data,
    } = this.state;

    return (
      <PageHeaderWrapper title="预测进度管理">
        <Card bordered={false}>
          <div className={styles.Manage}>
            <div className={styles.ManageForm}>
              <Form layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={6} sm={24}>
                    <FormItem key="forecastDate" label="被预测日期">
                      {getFieldDecorator('forecastDate', {
                        initialValue: forecastDate,
                      })(
                        <DatePicker
                          onChange={(date, dateString) => {
                            this.setState(
                              {
                                forecastDate: date,
                                forecastDateString: dateString,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                          placeholder="选择日期"
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="lv1ClassifyType" label="一级类目">
                      {getFieldDecorator('lv1ClassifyType', {
                        initialValue: lv1ClassifyType,
                      })(
                        <Radio.Group
                          onChange={e => {
                            this.setState(
                              {
                                lv1ClassifyType: e.target.value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        >
                          <Radio.Button value={0}>全部</Radio.Button>
                          <Radio.Button value={1}>水果</Radio.Button>
                          <Radio.Button value={2}>蔬菜</Radio.Button>
                        </Radio.Group>
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={10} sm={24}>
                    <FormItem key="cityId" label="城市">
                      {getFieldDecorator('cityIdList', {
                        initialValue: selectedCityList,
                      })(
                        <Select
                          placeholder="选择城市(支持多选)"
                          allowClear
                          mode="multiple"
                          onChange={e => {
                            this.setState(
                              {
                                selectedCityList: e,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        >
                          {cityList.map(item => (
                            <Select.Option value={item.id}>{item.name}</Select.Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col md={10} sm={24}>
                    <FormItem key="warehouse" label="仓库">
                      {getFieldDecorator('warehouseList', {
                        initialValue: selectedWarehouseList,
                      })(
                        <Select
                          placeholder="选择仓库(支持多选)"
                          allowClear
                          mode="multiple"
                          onChange={e => {
                            this.setState(
                              {
                                selectedWarehouseList: e,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        >
                          {warehouseList.map(item => (
                            <Select.Option value={item.id}>{item.name}</Select.Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </div>
            <Divider type="horizontal" />

            <Row gutter={{ md: 8, lg: 24, xl: 48 }} size="small">
              <Col>
                <div style={{ float: 'right' }}>
                  <Button
                    type="danger"
                    onClick={() => this.setState({ setProgressModalVisible: true })}
                  >
                    设置进度
                  </Button>
                  <Button
                    type="danger"
                    onClick={() => this.setState({ instructionModalVisible: true })}
                    style={{ marginLeft: '10px' }}
                  >
                    发送信号
                  </Button>
                </div>
              </Col>
            </Row>

            <StandardTable
              loading={loading}
              data={data}
              columns={this.columns}
              rowKey={record => record.id}
              onChange={this.handleStandardTableChange}
            />

            {this.renderSetProgressModel()}
            {this.renderInstructionModel()}
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default ProgressManage;
